#ifndef CommandWorker_H
#define CommandWorker_H

#include <QObject>
#include <QThread>
#include <QSerialPort>
#include "mainwindow.h"
#include <QQueue>
#include <QByteArray>
#include "utils.h"
#include <QList>
#include <QTimer>

struct ResponseParams {
    QByteArray command;     //发送数据
    QByteArray response;    //接收数据
    QString sendTime;       //发送时间
    QString receiveTime;    //接收时间
    int responseTime;       //响应时间
    QString status;         //应答状态
    ResponseParams() : command(""), response(""), sendTime(""), receiveTime(""), responseTime(0), status("") {}
    ResponseParams(QByteArray cmd , QByteArray rsp,QString snedtime, QString recvtime ,
                   int rsptime,QString st)
        : command(cmd), response(rsp), sendTime(snedtime), receiveTime(recvtime), responseTime(rsptime), status(st) {}
};

class CommandWorker : public QObject
{
    Q_OBJECT
public:
    explicit CommandWorker(QObject *parent = nullptr);

    void start(const QList<QByteArray>&commands);

    void logCommandResponse(const QByteArray &command, const QByteArray &response, const QString &sendTime, const QString &receiveTime, int responseTime, const QString &status);

signals:

    void commandResult(QByteArray result);

    void allTaskFinished();

    void OneFrameFinished(QString log);

    void openFailed(const QString& reason);


    //void CommandResponse(QByteArray cmd,QByteArray rsp,QDateTime sendtime,QDateTime recvtime);

    //void CommandStatus(QString status);


private:
    void HandleReadyRead();

    void sendNextCommand();

    void HandleTimeout();

    QString CheckFrame(QByteArray arr);

private:
    QSerialPort* m_serialPort;          //串口对象
    QQueue<QByteArray>m_commandQueue;   //命令队列
    QByteArray m_currentCommand;        //正在发送的命令
    QDateTime m_sendTime;              //记录命令发送时刻
    ResponseParams m_RspParams;        //当前应答数据
    int m_timeout;
    QByteArray m_receivedData;
    QTimer* m_timeoutTimer;
    //WorkerParams m_ReqPrams;
};

#endif // CommandWorker_H
